#include "transportLayer.hpp"
#include "dataTransmissionDds.hpp"
// #include "zeroCopy.hpp"


const size_t transportLayer::m_queMaxSize = 128;
std::shared_ptr<DataTransmissionDds> transportLayer::create(const int type)
{
    std::shared_ptr<DataTransmissionDds> ins;
    switch(type)
    {
        case ZEROCOPY_MOD:
            // ins = shared_ptr<DataTransmissionDds>(new zeroCopy);
        break;
    }
    return ins;
}


int transportLayer::init(const initializer_list<void *> attr)
{
    return 0;
}


int transportLayer::transmit(const std::vector<uint8_t> &data)
{
    //调用子类实现的传输函数
    return this->transmit(data.data(),data.size());
}

//等待接收数据返回
bool transportLayer::wait(const int64_t timeout)
{
    auto ret = false;
    std::unique_lock<std::mutex> guard(m_queMutex);
    if (0 == timeout) {
        ret = (false == m_recvQue.empty());
    } else if (timeout < 0) {//如果等待时长设置小于0，则永久等待
        m_queCond.wait(guard, [&](){
            return (false == this->m_recvQue.empty());
        });
        ret = true;
    } else { //设置等待时长
        ret = m_queCond.wait_for(guard,chrono::milliseconds(timeout),[&](){
            return (false == this->m_recvQue.empty());
        });
    }
    return ret;
}

size_t transportLayer::available()
{
    lock_guard<mutex> guard(m_queMutex);
    return m_recvQue.size();
}

void transportLayer::ayncRecv(const void *data,const size_t size)
{
    (void *)size;
    std::unique_lock<std::mutex> guard(m_queMutex);
    if (m_recvQue.size() >= m_queMaxSize) {
        this->release(m_recvQue.front());
        m_recvQue.pop();
    }

    m_recvQue.push(const_cast<void *>(data));
    m_queCond.notify_one();

}

//获取接收的数据
void* transportLayer::take()
{
    std::unique_lock<std::mutex> guard(m_queMutex);
    if( false == m_recvQue.empty()) {
        auto data = m_recvQue.front();
        m_recvQue.pop();
        return data;
    }
    return nullptr;
}